/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.modules.system.domain.Question;
import me.zhengjie.modules.system.domain.QuestionRatio;
import me.zhengjie.modules.system.domain.Teacher;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.mapper.TeacherMapper;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.QuestionService;
import me.zhengjie.modules.system.domain.vo.QuestionQueryCriteria;
import me.zhengjie.modules.system.mapper.QuestionMapper;
import me.zhengjie.utils.SecurityUtils;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-04-21
**/
@Service
@RequiredArgsConstructor
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {

    private final QuestionMapper questionMapper;

    private final UserMapper userMapper;

    private final TeacherMapper teacherMapper;

    @Override
    public QuestionRatio queryMyQuestionRito(){
        QuestionRatio questionRatio = new QuestionRatio();

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", SecurityUtils.getCurrentUserId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);


        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("teacherId",teacher.getId());
        queryWrapper1.eq("type",0);

        questionRatio.setSingleChoiceRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper1)));

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("teacherId",teacher.getId());
        queryWrapper2.eq("type",1);
        questionRatio.setMultipleChoiceRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper2)));


        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("teacherId",teacher.getId());
        queryWrapper3.eq("type",2);
        questionRatio.setJudgeRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper3)));


        QueryWrapper queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("teacherId",teacher.getId());
        queryWrapper4.eq("type",3);
        questionRatio.setCompletionRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper4)));


        QueryWrapper queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("teacherId",teacher.getId());
        queryWrapper5.eq("type",4);
        questionRatio.setShortAnswerRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper5)));

        return questionRatio;
    }

    @Override
    public QuestionRatio querySchoolQuestionRito(){

        QuestionRatio questionRatio = new QuestionRatio();

        User user = userMapper.selectById(SecurityUtils.getCurrentUserId());
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("schoolId",user.getDeptId());
        queryWrapper1.eq("type",0);

        questionRatio.setSingleChoiceRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper1)));

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("schoolId",user.getDeptId());
        queryWrapper2.eq("type",1);
        questionRatio.setMultipleChoiceRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper2)));


        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("schoolId",user.getDeptId());
        queryWrapper3.eq("type",2);
        questionRatio.setJudgeRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper3)));


        QueryWrapper queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("schoolId",user.getDeptId());
        queryWrapper4.eq("type",3);
        questionRatio.setCompletionRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper4)));


        QueryWrapper queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("schoolId",user.getDeptId());
        queryWrapper5.eq("type",4);
        questionRatio.setShortAnswerRatio(Math.toIntExact(questionMapper.selectCount(queryWrapper5)));

        return questionRatio;
    }
    @Override
    public PageResult<Question> queryAll(QuestionQueryCriteria criteria, Page<Object> page){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(currentUser.getDeptId());
        return PageUtil.toPage(questionMapper.findAll(criteria, page));
    }

    //获取管理员的试题
    public PageResult<Question> getAdminQuestionList(QuestionQueryCriteria criteria, Page<Object> page){

        return PageUtil.toPage(questionMapper.findAll(criteria, page));
    }

    //获取我的的试题
    public PageResult<Question> getMyQuestionList(QuestionQueryCriteria criteria, Page<Object> page){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(currentUser.getDeptId());

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        criteria.setTeacherId(teacher.getId());
        return PageUtil.toPage(questionMapper.findAll(criteria, page));
    }
    @Override
    public List<Question> queryAll(QuestionQueryCriteria criteria){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        criteria.setSchoolId(currentUser.getDeptId());
        return questionMapper.findAll(criteria);
    }


    public List<Question> queryAllByIds(List<Integer> ids){
        if(!ids.isEmpty()){
            return questionMapper.queryAllByIds(ids);
        } else {
            return new ArrayList<>();
        }

    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Question resources) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        if(teacher!=null && teacher.getId()!=null){
            resources.setTeacherId(teacher.getId());
        }

        resources.setSchoolId(currentUser.getDeptId());
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Question resources) {
        Question question = getById(resources.getId());
        question.copy(resources);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);
        question.setSchoolId(currentUser.getDeptId());
        saveOrUpdate(question);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Question> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Question question : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("题干", question.getName());
            map.put("学校id", question.getSchoolId());
            map.put("附件", question.getUrl());
            map.put("题型", question.getQuestionTypeId());
            map.put("解析", question.getAnalysis());
            map.put("难度", question.getDifficulty());
            map.put("是否发布", question.getIsPublish());
            map.put("必须按顺序填写", question.getIsOrder());
            map.put("是否上传图片", question.getIsUpload());
            map.put("创作人", question.getTeacherId());
            map.put("是否共享", question.getIsShare());
            map.put(" lastupdatetime",  question.getLastupdatetime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}